/**
 * 裁剪canvas矩形区域
 * @param {canvas} tarCanvas 裁剪源
 * @param {number} x 起点x
 * @param {number} y 起点y
 * @param {number} w 宽
 * @param {number} h 高
 * @returns dataURL
 */
function clipImage(image, x, y, w, h) {
  const width = w * devicePixelRatio
  const height = h * devicePixelRatio
  const canvas = new OffscreenCanvas(width, height)
  const ctx = canvas.getContext('2d')
  ctx.drawImage(image, x * devicePixelRatio, y * devicePixelRatio, width, height, 0, 0, width, height)

  return offScreenToDataUrl(canvas)
}

// offscreenCanvas to dataurl && return promise
function offScreenToDataUrl(canvas) {
  return new Promise((resolve, reject) => {
    canvas.convertToBlob().then((blob) => {
      const file = new FileReader()
      file.readAsDataURL(blob)
      file.onload = function(e) {
        resolve(e.target.result)
      }
    }).catch(err => reject(err))
  })
}

export default clipImage
